package com.erci.controller.admin;

import com.erci.constant.JwtClaimsConstant;
import com.erci.entity.DTO.LoginDTO;
import com.erci.entity.Login;
import com.erci.entity.User;
import com.erci.properties.JwtProperties;
import com.erci.result.Result;
import com.erci.service.LoginService;
import com.erci.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin(origins = "http://localhost:5173")
@RestController
@RequestMapping("/admin/api")
public class LoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private JwtProperties jwtProperties;
    @PostMapping("/login")
    public Result<Login> login(@RequestBody LoginDTO loginDTO) {
        User user = loginService.login(loginDTO);
        //TODO 生成token 校验
        if (user == null){
            return Result.error("用户名或密码错误");
        }
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        return Result.success(Login.builder().token(token).user(user).build());
    }
}
